package com.sdb.deepseek.service;

//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.io.OutputStream;
//import java.net.HttpURLConnection;
//import java.net.URL;
//import java.nio.charset.StandardCharsets;
//
//import com.google.gson.Gson;
//
//public class TongyiService {
//
//    static class Message {
//        String role;
//        String content;
//
//        public Message(String role, String content) {
//            this.role = role;
//            this.content = content;
//        }
//    }
//
//    static class RequestBody {
//        String model;
//        Message[] messages;
//
//        public RequestBody(String model, Message[] messages) {
//            this.model = model;
//            this.messages = messages;
//        }
//    }
//
//    public static void main(String[] args) {
//        try {
//            // 创建请求体
//            RequestBody requestBody = new RequestBody(
//                    //此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
//                    "qwen-plus",
//                    new Message[] {
//                            new Message("system", "You are a helpful assistant."),
//                            new Message("user", "头疼是怎么回事")
//                    }
//            );
//
//            // 将请求体转换为 JSON
//            Gson gson = new Gson();
//            String jsonInputString = gson.toJson(requestBody);
//
//            // 创建 URL 对象
//            URL url = new URL("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
//            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//
//            // 设置请求方法为 POST
//            httpURLConnection.setRequestMethod("POST");
//            httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
//            httpURLConnection.setRequestProperty("Accept", "application/json");
//
//            // 若没有配置环境变量，请用百炼API Key将下行替换为：String apiKey = "sk-xxx";
//            String apiKey = "sk-e4b9b757dfa347b1a83b9a4b9a767e3d";
//            String auth = "Bearer " + apiKey;
//            httpURLConnection.setRequestProperty("Authorization", auth);
//
//            // 启用输入输出流
//            httpURLConnection.setDoOutput(true);
//
//            // 写入请求体
//            try (OutputStream os = httpURLConnection.getOutputStream()) {
//                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
//                os.write(input, 0, input.length);
//            }
//
//            // 获取响应码
//            int responseCode = httpURLConnection.getResponseCode();
//            System.out.println("Response Code: " + responseCode);
//
//            // 读取响应体
//            try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
//                StringBuilder response = new StringBuilder();
//                String responseLine;
//                while ((responseLine = br.readLine()) != null) {
//                    response.append(responseLine.trim());
//                }
//                System.out.println("Response Body: " + response);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            System.exit(0);
//        }
//    }
//}


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Service
public class TongyiService {
    private static final String API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    String apiKey = "sk-e4b9b757dfa347b1a83b9a4b9a767e3d";

    private final Gson gson = new Gson();

    // 内部请求体类
    @Data
    @AllArgsConstructor
    private static class RequestBody {
        private String model;
        private Message[] messages;
    }

    // 消息类
    @Data
    @AllArgsConstructor
    private static class Message {
        private String role;
        private String content;
    }

    public String getChatResponse(String userInput) throws IOException {
        // 构建请求消息
        Message[] messages = {
                new Message("system", "智能医诊助手 赛博华佗"),
                new Message("user", userInput)
        };

        // 创建请求体
        RequestBody requestBody = new RequestBody("qwen-plus", messages);
        String jsonInput = gson.toJson(requestBody);

        // 创建HTTP连接
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        conn.setDoOutput(true);

        // 发送请求
        try(OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 处理响应
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {

                JsonObject response = gson.fromJson(br, JsonObject.class);
                return response.getAsJsonArray("choices")
                        .get(0).getAsJsonObject()
                        .getAsJsonObject("message")
                        .get("content").getAsString();
            }
        } else {
            throw new IOException("API请求失败，状态码：" + conn.getResponseCode());
        }
    }
}
